package com.itany.corejava.day16;

import javax.swing.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimerFrame {

    private JFrame jf;
    private JLabel jl1;
    private JLabel jl2;
    private String title;
    private Date targetDate;

    public TimerFrame(String title, Date targetDate) {
        this.title = title;
        this.targetDate = targetDate;
        jf=new JFrame(title+"倒计时牌");
        jl1=new JLabel("距离"+title+"还有：");
        jl2=new JLabel("xxxxxxxxxxxxxxxxxxxxx");
    }

    private void init(){
        jf.add(jl1, BorderLayout.NORTH);
        jf.add(jl2, BorderLayout.CENTER);
    }

    private void setStyle(){
        jl1.setFont(new Font("",Font.BOLD,20));
        jl2.setFont(new Font("",Font.BOLD,40));
        jl1.setForeground(Color.BLUE);
        jl2.setForeground(Color.RED);
    }

    private void addEventHandler(){
        new Thread(){
            @Override
            public void run() {
                while(true){

                    Date now=new Date();

                    long timeSeconds=(targetDate.getTime()-now.getTime())/1000;

                    if(timeSeconds<=0){
                        // jl2.setText("时间到！");

                        // jf.remove(jl1);
                        // jf.remove(jl2);
                        // jf.add(new JLabel("时间到"));
                        // jf.setVisible(true);


                        jf.dispose();
                        new TimeoutFrame(title,jf.getX(),jf.getY(),jf.getWidth(),jf.getHeight()).show();

                        break;
                    }

                    int days= (int) (timeSeconds/(60*60*24));
                    int hours= (int) (timeSeconds%(60*60*24)/(60*60));
                    int mins= (int) (timeSeconds%(60*60)/60);
                    int seconds= (int) (timeSeconds%60);

                    jl2.setText(days+"天"+hours+"时"+mins+"分"+seconds+"秒");

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public void show(){
        init();
        setStyle();
        addEventHandler();
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        String title=JOptionPane.showInputDialog("标题");
        String targetDateStr=JOptionPane.showInputDialog("目标时间");

        DateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        try {
            new TimerFrame(title,format.parse(targetDateStr)).show();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}
